package com.yuanhua.sim.netty.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 *  Zookeeper 工具类
 * @author yuanhua
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class ZookeeperUtil {

    @Autowired
    private ZooKeeper zooKeeper;

    /**
    判断当前节点是否存在
    */
    public Stat isExistNode(String path) throws Exception{
        return zooKeeper.exists(path,true);
    }
    /**
      创建节点
     */
    public String createNode(String path, Object object, ArrayList<ACL> zooDefs, CreateMode createMode) throws Exception {
        List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
        return  zooKeeper.create(path,object.toString().getBytes(),acl,createMode);
    }
    /**
      修改节点
     */
    public Stat updateNode(String path, Object object, int version) throws Exception {
        return zooKeeper.setData(path,object.toString().getBytes(),version);
    }
    /**
      删除节点
     */
    public void deleteNode(String path,int version) throws Exception {
        zooKeeper.delete(path,version);
    }


}

